<script setup name="BizUserTixianIndex">
import eventBus from "@/utils/eventBus";
import { usePagination } from "@/utils/composables";
import { parseTime, addDateRange } from "@/utils/aidex";
import { getDicts } from "@/api/system/dict/data";
import { selectDictLabel } from "@/utils/aidex";
import {
  listBizUserTixian,
  delBizUserTixian,
  getUserTixianAllAmount,
  torePay,
  rollbackAccount,
  getTransferBatchesDetails
} from "@/api/biz/bizUserTixian";
const { pagination, getParams, onSizeChange, onCurrentChange, onSortChange } =
  usePagination();
const router = useRouter();
const props = defineProps({
  id: {
    type: [Number, String],
    default: ""
  }
});
const data = ref({
  loading: false,
  allUserTixianAmount: undefined,
  /**
   * 详情展示模式
   * router 路由跳转
   * dialog 对话框
   * drawer 抽屉
   */
  formMode: "drawer",
  // 详情
  formModeProps: {
    visible: false,
    id: ""
  },
  // 搜索
  search: {
    name: "",
    phone: "",
    searchDate: [],
    status: "",
    userInfoId: props.id
  },
  // 批量操作
  batch: {
    enable: false,
    selectionDataList: []
  },
  // 列表数据
  dataList: [],
  tixianStatusList: []
});

// 页面挂载时 调用
onMounted(() => {
  getDataList();
  if (data.value.formMode === "router") {
    eventBus.on("get-data-list", () => {
      getDataList();
    });
  }
  getDicts("tixian_status").then((res) => {
    data.value.tixianStatusList = res.data;
  });
  findUserTixianAllAmount();
});
//
onBeforeUnmount(() => {
  if (data.value.formMode === "router") {
    eventBus.off("get-data-list");
  }
});
function statusFormat(row) {
  if (row.status) {
    console.log("xx", row.status);
    return selectDictLabel(data.value.tixianStatusList, row.status);
  } else {
    return "";
  }
}
// 每页数量切换
function sizeChange(size) {
  onSizeChange(size).then(() => getDataList());
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList());
}

// 字段排序
function sortChange(prop, order) {
  onSortChange(prop, order).then(() => getDataList());
}
// 查询
function getDataList() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.status && (params.status = data.value.search.status);
  data.value.search.userInfoId && (params.userInfoId = props.id);
  if (props.id) {
    listBizUserTixian(addDateRange(params, data.value.search.searchDate)).then(
      (res) => {
        data.value.loading = false;
        data.value.dataList = res.data.list;
        pagination.value.total = res.data.total;
      }
    );
  }
  data.value.loading = false;
}

function findUserTixianAllAmount() {
  data.value.loading = true;
  let params = getParams();
  data.value.search.userInfoId && (params.userInfoId = props.id);
  if (props.id) {
    getUserTixianAllAmount(params).then((res) => {
      data.value.loading = false;
      data.value.allUserTixianAmount = res.data;
    });
  }
  data.value.loading = false;
}

// 编辑
function onEdit(row) {
  data.value.formMode = "drawer";
  if (data.value.formMode === "router") {
    router.push({
      name: "routerName",
      params: {
        id: row.id
      }
    });
  } else {
    data.value.formModeProps.id = row.id;
    data.value.formModeProps.visible = true;
  }
}
function getDetails(row) {
  getTransferBatchesDetails(row).then((res) => {
    console.log(res.data);
  });
}
function rePay(row) {
  ElMessageBox.confirm("确认给「" + row.phone + "」重新付款吗？", "确认信息")
    .then(() => {
      torePay(row).then((res) => {
        if (res.code == 200) {
          ElMessage.success({
            message: "付款成功",
            center: true
          });
          getDataList();
        }
      });
    })
    .catch(() => {});
}

function rollbackUserAccount(row) {
  ElMessageBox.confirm("确认「" + row.phone + "」退回余额吗？", "确认信息")
    .then(() => {
      rollbackAccount(row).then((res) => {
        if (res.code == 200) {
          ElMessage.success({
            message: "退回成功",
            center: true
          });
          getDataList();
        }
      });
    })
    .catch(() => {});
}
// 添加
function onAdd() {
  data.value.formModeProps.id = "";
  data.value.formMode = "dialog";
  data.value.formModeProps.visible = true;
}
// 批量删除 单独删除
function onDel(row) {
  const ids =
    row.id ||
    data.value.batch.selectionDataList.map((item) => {
      return item.id;
    });
  const names =
    row.postName ||
    data.value.batch.selectionDataList.map((item) => {
      return item.name;
    });
  if (ids.length > 0) {
    ElMessageBox.confirm("确认删除「" + names + "」吗？", "确认信息")
      .then(() => {
        delBizUserTixian(ids).then((res) => {
          getDataList();
          if (res.code == 200)
            ElMessage.success({
              message: "删除成功",
              center: true
            });
        });
      })
      .catch(() => {});
  } else {
    ElMessage.warning({ message: "请选择数据", center: true });
  }
}
</script>

<template>
  <div>
    <page-main style="height: calc(100vh - 200px); margin: 0">
      <search-bar>
        <el-form
          :model="data.search"
          size="default"
          label-width="auto"
          label-suffix=""
        >
          <el-row :gutter="30">
            <el-col :span="14">
              <el-form-item label="提现时间">
                <el-date-picker
                  v-model="data.search.searchDate"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-select v-model="data.search.status" clearable>
                  <el-option
                    v-for="(item, index) in data.tixianStatusList"
                    :key="index"
                    :value="item.dictValue"
                    :label="item.dictLabel"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item>
                <el-button type="primary" @click="currentChange()">
                  <template #icon>
                    <el-icon>
                      <svg-icon name="ep:search" />
                    </el-icon>
                  </template>
                  查询
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="">
                总提现:
                <span style="margin-left: 20px"
                  >¥：{{
                    parseFloat(
                      data.allUserTixianAmount ? data.allUserTixianAmount : 0
                    ).toFixed(2)
                  }}</span
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </search-bar>

      <div style="height: calc(100vh - 440px); overflow-y: hidden">
        <el-table
          ref="table"
          v-loading="data.loading"
          class="list-table"
          :data="data.dataList"
          border
          highlight-current-row
          row-key="id"
          @sort-change="sortChange"
          @selection-change="data.batch.selectionDataList = $event"
        >
          >
          <el-table-column type="selection" align="center" />
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="id"
            label="流水号"
            show-overflow-tooltip
            align="center"
            width="175"
          >
            <template v-slot="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>

          <el-table-column
            prop="money"
            label="提现金额"
            show-overflow-tooltip
            align="right"
            width="100"
          >
            <template v-slot="scope" style="font-weight: bold">
              ¥&nbsp;{{ scope.row.money }}
            </template>
          </el-table-column>

          <el-table-column
            prop="status"
            label="状态"
            show-overflow-tooltip
            align="center"
            width="120"
          >
            <template v-slot="scope">
              <!-- （0待审核 1 已打款 2 已到账 -1 驳回 99 打款失败） -->
              <el-tag :class="'ml-' + scope.row.status" type="success"
                >{{ statusFormat(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
            prop="createTime"
            label="申请时间"
            show-overflow-tooltip
            width="175"
          >
            <template v-slot="scope">
              {{ scope.row.createTime }}
            </template>
          </el-table-column>

          <el-table-column
            prop="wxPayNo"
            label="微信流水号"
            show-overflow-tooltip
            width="320"
            align="center"
          >
            <template v-slot="scope">
              {{ scope.row.wxPayNo }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" show-overflow-tooltip>
            <template v-slot="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
        :current-page="pagination.page"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </page-main>
    <FormMode
      v-if="['dialog', 'drawer'].includes(data.formMode)"
      :id="data.formModeProps.id"
      v-model="data.formModeProps.visible"
      :mode="data.formMode"
      @success="getDataList"
    />
  </div>
</template>

<style lang="scss" scoped>
.el-pagination {
  display: flex;
  justify-content: center;
  align-items: center;
}
.ml-99 {
  background-color: rgb(255 0 0 / 30%);
  color: #f00;
  border: 1px solid #f00;
}
</style>
